package com.come4loves.game.module.card.facade.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.come4loves.core.lock.ChainLock;
import com.come4loves.core.lock.LockUtils;
import com.come4loves.core.result.Result;
import com.come4loves.core.result.TResult;
import com.come4loves.game.constent.GameStatusCodeConstant;
import com.come4loves.game.dbproxy.entity.Card;
import com.come4loves.game.module.card.constant.CardType;
import com.come4loves.game.module.card.dao.CardDao;
import com.come4loves.game.module.card.facade.CardFacade;
import com.come4loves.game.module.card.model.CardModel;

@Component
public class CardFacadeImpl implements CardFacade {

	public static Logger LOGGER = LoggerFactory.getLogger(CardFacadeImpl.class);

	@Autowired
	public CardDao cardDao;
	
	@Override
	public TResult<List<CardModel>> getCollectionCard(long actorId) {
		Card cards = cardDao.getCard(actorId);
		if (cards.isNewEntity()) {
			ChainLock lock = LockUtils.getLock(cards);
			try {
				lock.lock();
				cards.initCard4Fresh();
				cardDao.updateQueue(cards);
			} catch (Exception exception) {
				LOGGER.error("{}" ,exception);
			} finally {
				lock.unlock();
			}
		}
		List<CardModel> models = new ArrayList<CardModel>();
		models.addAll(cards.generCardsMap.values());
		models.addAll(cards.equipCardsMap.values());
		models.addAll(cards.spellCardsMap.values());
		models.addAll(cards.unitCardsMap.values());
		return TResult.sucess(models);
	}

	@Override
	public Result modifyCardPriority(long actorId, CardType cardType, int cardId, int priority) {
		Card cards = cardDao.getCard(actorId);
		CardModel cardModel = cardDao.getCardModel(actorId, cardType, cardId);
		if(cardModel == null) {
			return Result.valueOf(GameStatusCodeConstant.CARD_TYPE_ERROR);
		}
		ChainLock lock = LockUtils.getLock(cards);
		try {
			lock.lock();
			cardModel.priority = priority;
			cardDao.putCardModel(actorId, cardModel);
			cardDao.updateQueue(cards);
		} catch (Exception exception) {
			LOGGER.error("{}" ,exception);
		} finally {
			lock.unlock();
		}
		return Result.valueOf();
	}


}
